package com.atguigu.gmall.weball.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.feign.cart.CartFeignClient;
import com.atguigu.gmall.feign.order.OrderFeignClient;
import com.atguigu.gmall.feign.user.UserFeignClient;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.user.UserAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.math.BigDecimal;
import java.util.List;

@Controller
public class OrderController {

    @Autowired
    CartFeignClient cartFeignClient;

    @Autowired
    UserFeignClient userFeignClient;

    @Autowired
    OrderFeignClient orderFeignClient;
    /**
     * 来到 订单确认页
     * @return
     */
    @GetMapping("/trade.html")
    public String tradePage(Model model){

        //准备数据
        //1、detailArrayList： 所有要参与结算的商品列表  {imgUrl、skuName、orderPrice、skuNum、有货}
        Result<List<OrderDetail>> order = cartFeignClient.getCartInfoForOrder();
        if(order.isOk()){
            model.addAttribute("detailArrayList",order.getData());
        }

        //2、totalNum：        商品总数量
        List<OrderDetail> data = order.getData();
        Integer totalNum = data.stream()
                .map(item -> item.getSkuNum())
                .reduce((i1, i2) -> i1 + i2)
                .get();

        model.addAttribute("totalNum",totalNum);


        //3、totalAmount：     商品总价格
        BigDecimal totalAmount = data.stream()
                .map(item -> item.getOrderPrice().multiply(new BigDecimal(item.getSkuNum() + "")))
                .reduce((i1, i2) -> i1.add(i2))
                .get();

        model.addAttribute("totalAmount",totalAmount);


        //4、userAddressList： 用户地址列表
        Result<List<UserAddress>> userAddress = userFeignClient.getUserAddress();
        if(userAddress.isOk()){
            model.addAttribute("userAddressList",userAddress.getData());
        }

        //5、tradeNo：         交易追踪号；防止重复提交
        Result<String> result = orderFeignClient.generateOrderTradeNo();
        if(result.isOk()){
            model.addAttribute("tradeNo",result.getData());
        }

        return "order/trade";
    }
}
